package com.tdk.wifidirectserver.ui.main

import android.Manifest
import android.content.Context
import android.net.wifi.p2p.WifiP2pDevice
import android.net.wifi.p2p.WifiP2pManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.tdk.common.util.PermissionUtil
import com.tdk.wifidirectserver.MainActivity
import com.tdk.wifidirectserver.adapter.DeviceAdapter
import com.tdk.wifidirectserver.adapter.WifiP2pDeviceDiff
import com.tdk.wifidirectserver.databinding.FragmentMainBinding
import com.tdk.wifidirectserver.util.ConnectivityUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainFragment : Fragment() {
    val TAG = "MainFragment"


    private lateinit var binding: FragmentMainBinding

    lateinit var viewModel: MainViewModel

    companion object {
        fun newInstance() = MainFragment()
    }


    private val adapter = DeviceAdapter(WifiP2pDeviceDiff())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch(Dispatchers.IO) {
            val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                PermissionUtil.requestPermissions(
                    this@MainFragment,
                    arrayOf(
                        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.NEARBY_WIFI_DEVICES
                    ),
                )
            } else {
                PermissionUtil.requestPermissions(
                    this@MainFragment,
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
                )
            }
            if (!result.second) {
                // 切换协程
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@MainFragment.requireContext(), "请授予定位权限", Toast.LENGTH_SHORT).show()
                }
            }
        }

        viewModel.isScanning.observe(this) {
            Log.d(TAG, "isScanning:   $it")
            if (it) {
                binding.scanStatus.text = "ScanStatus: Scanning"
            } else {
                binding.scanStatus.text = "ScanStatus: Ideal"
            }
        }

        viewModel.localWifiP2pDevice.observe(this) {
            Log.d(TAG, "localWifiP2pDevice:   $it")
            binding.tvLocalDeviceInfo.text = "$it"
        }

        viewModel.scanWifiP2pDeviceList.observe(this) {
            Log.d(TAG, "scanWifiP2pDeviceList: $it")
            adapter.submitList(it)
            adapter.notifyDataSetChanged()
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentMainBinding.inflate(inflater, container, false)
        binding.startScanBt.setOnClickListener {
            viewModel.startScan()
        }
        binding.stopScanBt.setOnClickListener {
            viewModel.stopScan()
        }

        binding.btStartP2p.setOnClickListener {
            viewModel.initConfig()
        }


        if (ConnectivityUtil.getInstance(this.requireActivity()).isOpenWifi()) {
            ConnectivityUtil.getInstance(this.requireActivity()).openWifi()
        }
        if (!ConnectivityUtil.getInstance(this.requireActivity()).isEnableWifiDirect()) {
            Toast.makeText(this.requireContext(), "Wifi Direct is not supported", Toast.LENGTH_SHORT).show()
        }

        adapter.onItemClickListener = {
            Log.d(TAG, "onItemClick: $it")
            if (it.status == WifiP2pDevice.INVITED) {
                viewModel.cancelConnect(object : WifiP2pManager.ActionListener {
                    override fun onSuccess() {
                        Log.d(TAG, "cancelConnect onSuccess")
//                        viewModel.connect(it)
                    }

                    override fun onFailure(reason: Int) {
                        Log.d(TAG, "cancelConnect onFailure: $reason")
                    }
                })

            }
            if (it.status == WifiP2pDevice.AVAILABLE) {
                viewModel.connect(it)
            }
        }
        adapter.onItemLongClickListener = { deviceInfoBean ->
            Log.d(TAG, "onItemLongClick: $deviceInfoBean")
            viewModel.disconnect()
        }
        binding.devicesListView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        binding.devicesListView.adapter = adapter

        binding.btCreateGroup.setOnClickListener {
            viewModel.createGroup()
        }
        binding.btConnectWithPassword.setOnClickListener {
            viewModel.connectWithPassword("12345678", " ")
        }

        viewModel.connectedWifiP2pGroup.observe(viewLifecycleOwner, Observer {
            Log.d(TAG, "connectedWifiP2pGroup: $it")
        })

        return binding.root
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is MainActivity) {
            viewModel = context.viewModel
        }

    }

}